﻿using Const;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;


public class UIController : MonoBehaviour
{
    public Button btnPlay;
    public Button btnAgain;
    public Text curScore;
    public Text bestScore;

    public Text btnPlayText;
    public Text btnAgainText;

    public void ChangeUI(EState state)
    {
        switch (state)
        {
            case EState.START:
                btnPlay.gameObject.SetActive(true);
                btnAgain.gameObject.SetActive(false);
                curScore.gameObject.SetActive(false);
                bestScore.gameObject.SetActive(false);
                break;
            case EState.ING:
                curScore.gameObject.SetActive(true);
                btnPlay.gameObject.SetActive(false);
                btnAgain.gameObject.SetActive(false);
                bestScore.gameObject.SetActive(false);
                break;
            case EState.END:
                btnAgain.gameObject.SetActive(true);
                curScore.gameObject.SetActive(true);
                bestScore.gameObject.SetActive(true);
                btnPlay.gameObject.SetActive(false);
                SaveAndShowScore();
                break;
        }
    }

    public void OnPlayGame()
    {
        GameManager.ins.state = EState.ING;
    }

    public void OnPlayGameAgain()
    {
        GameManager.ins.state = EState.START;
        GameManager.ins.score = 0;
        GameManager.ins.ResetWall();
    }

    private void Start()
    {
        SetUITween(btnPlayText);
        SetUITween(btnAgainText);
    }

    void Update()
    {
        if (GameManager.ins.state == EState.ING)
        {
            GameManager.ins.score += Time.deltaTime;
            curScore.text = GameManager.ins.score.ToString("f1");
        }
    }

    private void SaveAndShowScore()
    {
        var bestScore = 0.0f;
        if (PlayerPrefs.HasKey("best"))
        {
            bestScore = PlayerPrefs.GetFloat("best");
        }

        if (bestScore < GameManager.ins.score)
        {
            bestScore = GameManager.ins.score;
            PlayerPrefs.SetFloat("best", bestScore);
        }
        
        this.bestScore.text = "最佳  " + bestScore.ToString("f1");
    }

    private void SetUITween(Graphic text)
    {
        DOTween.ToAlpha
        (
            () => text.color,
            (c) => text.color = c,
            0.5f,
            2f
        ).SetEase(Ease.OutSine).SetLoops(-1, LoopType.Yoyo);
    }
}